﻿using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net.Configuration;
using System.Web.Configuration;

namespace LenderClearingHouse
{
  public partial class RequestPropertyMessage : PageBase
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        Button1.Attributes.Add("onclick", " this.disabled = true; "
          + ClientScript.GetPostBackEventReference(Button1, null) + ";");
      }
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
      SetFocus(TextArea);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
      string apn = Request.QueryString["Apn"];

      DataAccess da = new DataAccess();
      DataTable dt = da.ExecuteSQL("select * from UserAccounts where UserId = " + CurrentUser.UserId);

      string sendListKey = CurrentUser.SubRole == UserSubRole.LVReo ? "LvreoNotificationList" : "SdreoNotificationList";
      dt = da.ExecuteSQL("select [Value] from Config where [Key] = '" + sendListKey + "'");
      sendListKey = dt.Rows[0][0].ToString();

      try
      {
        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;

        System.Configuration.Configuration config =
          WebConfigurationManager.OpenWebConfiguration("~/");
        SmtpSection smtpSection = (SmtpSection)config.GetSection("system.net/mailSettings/smtp");

        MailMessage msg = new MailMessage();
        msg.From = new MailAddress(smtpSection.Network.UserName);

        string[] sendListMails = sendListKey.Split(';');
        foreach (string mail in sendListMails)
        {
          msg.To.Add(mail);
        }
        
        msg.Subject = "property " + apn + " reserve request from "
          + CurrentUser.FName + " " + CurrentUser.LName;
        msg.IsBodyHtml = true;
        msg.Body = File.ReadAllText(Server.MapPath("~/Template/PropertyRequest.htm"));
        msg.Body = msg.Body.Replace("%InvestorName%", CurrentUser.FName + " " + CurrentUser.LName).Replace(
          "%APN%", apn).Replace("%RequestDate%", DateTime.Today.ToShortDateString()).Replace(
          "%Message%", TextArea.Value);

        client.Send(msg);

        da.ExecuteSQLNonQuery(
          string.Format("insert into PropertyRequests(UserId, Apn) values({0}, '{1}')",
          CurrentUser.UserId, apn));

        ScriptManager.RegisterStartupScript(this, this.GetType(), "key",
          "alert('Email has been sent successfully'); CloseForm();", true);
      }
      catch(Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
            "key", "alert('Error: " + ex.Message + "');", true);
      }
    }
  }
}